import {
  GET_COURSE_DETAIL,
  GET_COURSE_LIST,
  GET_LESSON_DETAIL,
  GET_LESSON_LIST,
  SET_CURRENT_COURSE
} from "../../mutation-types";
import Request from "../../../utils/ajax";
import { Toast } from "../../../utils/modal";

const {
  courseList,
  courseDetail,
  lessonList,
  lessonDetail,
  completeTask,
  check_study
} = Request.course;

export const reqCourseList = async (
  { commit, state, rootState },
  { type = 2 }
) => {
  try {
    const { token } = rootState.User;
    const { data } = await courseList({ token, type });
    commit(GET_COURSE_LIST, { type, ...data });
  } catch (e) {
    console.log(e);
  }
};

export const reqCourseDetail = async ({ commit, rootState }, { id }) => {
  try {
    const { token } = rootState.User;
    const { data } = await courseDetail({ token, id });
    commit(GET_COURSE_DETAIL, data);
  } catch (e) {
    console.log(e);
  }
};

export const reqLessonList = async ({ commit, rootState }, { id }) => {
  try {
    const { token } = rootState.User;
    const { data } = await lessonList({ token, id });
    console.log(data);
    commit(GET_LESSON_LIST, data);
  } catch (e) {
    console.log(e);
  }
};

export const reqLessonDetail = async (
  { commit, rootState },
  { id, type_id }
) => {
  try {
    const { token } = rootState.User;
    commit(SET_CURRENT_COURSE, { type_id, id });
    const { data } = await lessonDetail({ token, id, type_id });
    commit(GET_LESSON_DETAIL, {
      lessonDetail: data,
      lessonType: type_id
    });
  } catch (e) {
    console.log(e);
  }
};

export const reqCompleteTask = async (
  { rootState },
  { id, type_id, answer_id, recording }
) => {
  try {
    const { token } = rootState.User;

    type_id = parseInt(type_id);

    const options =
      type_id === 1
        ? { type_id, id, token }
        : type_id === 2
        ? { type_id, id, token, recording }
        : type_id === 3
        ? { token, type_id, id, answer_id }
        : { type_id, id, token, recording };
    const { data } = await completeTask(options);
  } catch (e) {
    throw new Error(e);
  }
};

export const studyMore5 = async ({ rootState }, { id }) => {
  try {
    const { token } = rootState.User;
    const {
      data: { status }
    } = await check_study({ token, id });
    if (status === 1) {
      Toast({ title: "你今天已经学了3课了~好好休息一下吧" });
      return true;
    }
    return false;
  } catch (e) {}
};
